//引入使用SockJS
import SockJS from "sockjs-client";
import Stomp from "stompjs";
import { token } from "@/utils";
//请求地址
const baseUrl = "http://localhost:8888/ws?token=" + token.get();
//请求头
const header = {
  token: token.get(),
};
//stomp客户端
export let stompClient: Stomp.Client;
//连接状态
let connetStatus = false;
/**
 * 初始化连接
 */
export const initSocket = () => {
  conn();
  // setInterval(() => {
  //   //根据连接状态
  //   if (connetStatus) {
  //     try {
  //       //发送请求
  //       stompClient.send(
  //         "/app/hello",
  //         header,
  //         JSON.stringify({ name: "wangau" })
  //       );
  //     } catch (error) {
  //       conn();
  //     }
  //   }
  // }, 10000);
};

export const send = (url: string, data: any) => {
  stompClient.send(url, header, JSON.stringify(data));
};

/**
 * 连接
 */
export const conn = () => {
  let socket = new SockJS(baseUrl);

  stompClient = Stomp.over(socket);

  let header = {};
  stompClient.connect(
    header,
    () => {
      connetStatus = true;
      //设置订阅
      const greetings = stompClient.subscribe(
        "/greetings",
        (res: any) => {
          console.log(res);
        },
        header
      );
      stompClient.subscribe("/topic/messages", (res: any) => {
        console.log("处理到messages");
      });
      stompClient.subscribe("/topic/to", (res: any) => {
        console.log("/topic/to");
      });
      stompClient.subscribe("/user/topic/to-user", (res: any) => {
        console.log("/user/topic/to-user");
      });
      stompClient.subscribe("/topic/simp-to", (res: any) => {
        console.log("/user/topic/simp-to");
      });
      stompClient.subscribe("/user/topic/simp-to-user", (res: any) => {
        console.log("/user/topic/simp-to-user");
      });
    },
    (err: any) => {
      console.log("error");
      console.log(err);
    }
  );
};

/**
 * 断开
 */
export const close = () => {
  if (stompClient) {
    stompClient.disconnect(() => {
      console.log("============connect release============");
      connetStatus = false;
    });
  }
};
